﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Configuration;

namespace Subsidiary.BookSearch
{
    public class Search
    {
        public BookItem SearchBook(string bookName)
        {
            BookItem book = new BookItem();
            try
            {
                Crawler crawler = new Crawler();
                string urlOfSearch = string.Format("http://www.amazon.cn/s?field-keywords={0}", bookName);
                string htmlOfSearch = crawler.Grab(urlOfSearch);
                Analysis analysis = new Analysis();
                string urlOfDetail = string.Empty;
                string urlOfPicture = string.Empty;
                analysis.PickupSearch(book, htmlOfSearch, ref urlOfDetail, ref urlOfPicture);
                string htmlOfDetail = crawler.Grab(urlOfDetail);
                analysis.PickupDetail(book, htmlOfDetail);
                book.Name = bookName;
                SavePicture(urlOfPicture, book);
                book.Id = Guid.NewGuid();
                book.Picture = string.Format("http://study-for-kevin.googlecode.com/svn/trunk/images/blog/books/{0}.jpg", book.Name);
                book.Status = "未读";
                book.Comment = "无";
                return book;
            }
            catch (Exception ex)
            {
                return book;
            }
        }

       void SavePicture(string urlOfPicture, BookItem book){
           //修改tempFile地址
           string tempFile = string.Format("{0}{1}{2}.jpg", ConfigurationManager.AppSettings["PictureFolder"], Path.DirectorySeparatorChar, book.Name);
           using (WebClient client = new WebClient())
           {
               client.DownloadFile(urlOfPicture, tempFile);
           }
        }

       
    }
}
